package com.cysyz.mylib.utils.init;

import com.cysyz.mylib.utils.MyStringUtils;
import org.springframework.util.ReflectionUtils;

import java.lang.reflect.Method;

public class InitUtils {
	public static void init2NullIfZero(Object bean, String... propertyNames) {
		if (bean != null && propertyNames != null && propertyNames.length > 0) {
			for (String propertyName : propertyNames) {
				String setterName = getSetter(propertyName);
				String getterName = getGetter(propertyName);
				Method getterMethod = null;
				Method setterMethod = null;
				try {
					getterMethod = ReflectionUtils.findMethod(bean.getClass(), getterName);
					Object value = getterMethod.invoke(bean);
					if (value != null && (value.toString().trim().equals("0") || value.toString().trim().equals(""))) {
						DataType[] dataTypes = DataType.values();
						for (DataType dataType : dataTypes) {
							Class dataTypeClass = dataType.getDataTypeClass();
							if (value.getClass() == dataTypeClass) {
								
								setterMethod = dataType.getSetter(bean, setterName);
								setterMethod.invoke(bean, new Object[] {null});
								break;
							}
						}
					}
				} catch (Exception e) {
					throw new RuntimeException(e);
				}
			}
		}
	}

	public static String getSetter(String propertyName) {
		return MyStringUtils.getSetter(propertyName);
	}

	public static String getGetter(String propertyName) {
		return MyStringUtils.getGetter(propertyName);
	}
}	
